﻿using CSLC.WeChat.PublicAccount;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace CSLC.WeChat.UI.MVC.Controllers
{
    public class MassMessageController : Controller
    {
        //
        // GET: /MassMessage/

        public ActionResult Index()
        {
            ViewBag.SelectOption = AccountInfoCollection.AccountInfos;
            return View();
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUser(string userName)
        {
            ErrorMessage errorMessage;
            string[] openIds = UserManagement.GetUserList(userName);
            //这个判断是针对查询次数限制的，每天不能超过几次
            if (openIds == null || openIds.Count() < 1)
            {
                openIds = new string[] { "oZ1szwlKCik6lTGBdTdl5gXhrvzM", "oZ1szwrgRQ3GWrA90K_szw58Or-U" };
            }
            IDictionary<string, string> userList = new Dictionary<string, string>();
            if (openIds != null && openIds.Length > 0)
            {
                foreach (string openId in openIds)
                {
                    UserInfo user = UserManagement.GetUserInfo(userName, openId, out errorMessage);
                    if (errorMessage.IsSuccess && user != null)
                        userList.Add(user.nickname, openId);
                }
                
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string re=jss.Serialize(userList);
                return Content(re);
            }
            else
                return null;
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="userIdList"></param>
        /// <param name="accountName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public ActionResult SendToUsers(string userIdList,string accountName,string msg)
        {
            if (!string.IsNullOrEmpty(userIdList))
            {
                ErrorMessage errorMessage;
                IList<string> openIds = userIdList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (openIds.Count < 2)
                {
                    openIds.Add("");
                }

                long msgId = MassMessage.Send(accountName, openIds, MassMessageTypeEnum.text, msg, out errorMessage);
                if (errorMessage.IsSuccess)
                {
                    return Content(string.Format("id:{0},text:{1}", msgId, msg));
                }
                else
                    return Content("NO");
                    //return Content(string.Format("群发消息失败。{0}", errorMessage));
            }
            else
            {
                return Content("请选择要发送的用户！");
            }
        }
        /// <summary>
        /// 预览群发消息
        /// </summary>
        /// <param name="userIdList"></param>
        /// <param name="accountName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public ActionResult PreView(string userIdList, string accountName, string msg)
        {
            string re=null;
            if (!string.IsNullOrEmpty(userIdList))
            {
                ErrorMessage errorMessage;
                string openId = userIdList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[0];
                long msgId = MassMessage.Preview(accountName, openId, MassMessageTypeEnum.text, msg, out errorMessage);
                if (errorMessage.IsSuccess)
                {
                    re = string.Format("预览消息成功。id:{0},text:{1}", msgId, msg);
                    
                }
                else
                    re = string.Format("预览消息失败。{0}", errorMessage);
            }
            else
            {
                re="请选择要发送的用户！";
            }
            return Content(re);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="messageIDS"></param>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public ActionResult DeleteMessages(string messageIDS, string accountName)
        {
            if (!string.IsNullOrEmpty(messageIDS))
            {
                //IList<long> messageIdList = new List<long>();
                //string[] idArr = messageIDS.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                //foreach (string str in idArr)
                //{
                //    messageIdList.Add(Convert.ToInt64(str));
                //}
                //IList<ErrorMessage> errList = new List<ErrorMessage>();
                //foreach (long messageid in messageIdList)
                //{
                //    ErrorMessage em = MassMessage.Delete(accountName, messageid);
                //    if (!em.IsSuccess) return Content("NO");
                //    errList.Add(em);
                //}
                ErrorMessage em = MassMessage.Delete(accountName, long.Parse(messageIDS));
                if (!em.IsSuccess) return Content(string.Format("错误编码：{0},错误信息：{1}",em.errcode,em.errmsg));
                return Content("OK");
            }
            else
            {
                return Content("请选择要删除的消息！");
            }
        }
        /// <summary>
        /// 查询消息发送状态
        /// </summary>
        /// <param name="messageID"></param>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public ActionResult GetMessageStates(string messageID, string accountName)
        {
            if (!string.IsNullOrEmpty(messageID))
            {
                ErrorMessage errorMessage;
                long msgId = long.Parse(messageID);
                bool success = MassMessage.GetStatus(accountName, msgId, out errorMessage);
                if (errorMessage.IsSuccess)
                    return Content(string.Format("消息群发{0}。", success ? "成功" : "失败"));
                else
                    return Content(string.Format("获取消息群发状态失败。{0}", errorMessage));
            }
            return Content("请选择要查询的消息！");
        }
        /// <summary>
        /// 获取用户分组
        /// </summary>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public ActionResult GetUserGroups(string accountName)
        {
            
            ErrorMessage errorMessage;
            IDictionary<string, string> groupList = new Dictionary<string, string>();
            
            groupList.Add("所有分组", "-1");
            UserGroup[] groups = UserManagement.GetGroup(accountName, out errorMessage);
            if (errorMessage.IsSuccess && groups != null && groups.Length > 0)
            {
                foreach (UserGroup group in groups)
                    groupList.Add(string.Format("{0}({1})", group.name, group.count), group.id.ToString());
            }
            else
                return Content("NO");

            JavaScriptSerializer jss = new JavaScriptSerializer();
            string re = jss.Serialize(groupList);
            return Content(re);
        }
        /// <summary>
        /// 以组发送消息
        /// </summary>
        /// <param name="GroupList"></param>
        /// <param name="accountName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public ActionResult SendByGroup(string GroupTag, string accountName, string msg)
        {
            if (!string.IsNullOrEmpty(GroupTag))
            {
                ErrorMessage errorMessage;
                bool isToAll = GroupTag=="-1";
                string groupId = isToAll ? "" : GroupTag;
                long msgId = MassMessage.Send(accountName, isToAll, groupId, MassMessageTypeEnum.text, msg, out errorMessage);
                if (errorMessage.IsSuccess)
                {
                    return Content(string.Format("id:{0},text:{1}", msgId, msg));
                }
                else
                    return Content("NO");
            }
            else
                return Content("请选择分组");
        }

    }
}
